package com.xjk.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author 许嘉凯 JM032791
 * @date 2024-09-05
 */
public class HttpRequestUtil {


  public static String sendPost(String urlStr, String jsonInputString, Map<String, String> headers) throws Exception {
    URL url = new URL(urlStr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);

    // 添加请求头
    for (Map.Entry<String, String> entry : headers.entrySet()) {
      connection.setRequestProperty(entry.getKey(), entry.getValue());
    }

    // 发送请求体
    try (OutputStream os = connection.getOutputStream()) {
      byte[] input = jsonInputString.getBytes("utf-8");
      os.write(input, 0, input.length);
    }
    getResponsePre(connection);
    // 读取响应
    StringBuilder response = new StringBuilder();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
      String responseLine;
      while ((responseLine = br.readLine()) != null) {
        response.append(responseLine.trim());
      }
    }

    connection.disconnect();
    return getResponseStr(response);
  }

  public static String sendGet(String urlStr, Map<String, String> headers) throws Exception {
    URL url = new URL(urlStr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");

    // 添加请求头
    for (Map.Entry<String, String> entry : headers.entrySet()) {
      connection.setRequestProperty(entry.getKey(), entry.getValue());
    }

    getResponsePre(connection);
    // 读取响应
    StringBuilder response = new StringBuilder();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
      String responseLine;
      while ((responseLine = br.readLine()) != null) {
        response.append(responseLine.trim());
      }
    }

    connection.disconnect();
    return getResponseStr(response);
  }

  private static void getResponsePre(HttpURLConnection connection) throws IOException {
    // 获取响应状态码
//    int responseCode = connection.getResponseCode();
//    System.out.println("===================请求响应===================");
//    System.out.println("Response Code : " + responseCode);

  }

  public static String sendPut(String urlStr, String body, Map<String, String> headers) throws Exception {
    URL url = new URL(urlStr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("PUT");
    connection.setDoOutput(true);  // 因为PUT请求需要发送数据
    connection.setRequestProperty("Content-Type", "application/json; utf-8");

    // 添加请求头
    for (Map.Entry<String, String> entry : headers.entrySet()) {
      connection.setRequestProperty(entry.getKey(), entry.getValue());
    }

    // 发送请求体
    try (OutputStream os = connection.getOutputStream()) {
      byte[] input = body.getBytes(StandardCharsets.UTF_8);
      os.write(input, 0, input.length);
    }

    getResponsePre(connection);

    // 读取响应
    StringBuilder response = new StringBuilder();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
      String responseLine;
      while ((responseLine = br.readLine()) != null) {
        response.append(responseLine.trim());
      }
    }

    connection.disconnect();
    return getResponseStr(response);
  }


  public static String sendDelete(String urlStr, Map<String, String> headers) throws Exception {
    URL url = new URL(urlStr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("DELETE");

    // 添加请求头
    for (Map.Entry<String, String> entry : headers.entrySet()) {
      connection.setRequestProperty(entry.getKey(), entry.getValue());
    }

    getResponsePre(connection);

    // 读取响应
    StringBuilder response = new StringBuilder();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
      String responseLine;
      while ((responseLine = br.readLine()) != null) {
        response.append(responseLine.trim());
      }
    }

    connection.disconnect();
    return getResponseStr(response);
  }

  public static String sendOptions(String urlStr, Map<String, String> headers) throws Exception {
    URL url = new URL(urlStr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("OPTIONS");

    // 添加请求头
    for (Map.Entry<String, String> entry : headers.entrySet()) {
      connection.setRequestProperty(entry.getKey(), entry.getValue());
    }

    getResponsePre(connection);
    // 读取响应头
    StringBuilder responseHeaders = new StringBuilder();
    Map<String, java.util.List<String>> headerFields = connection.getHeaderFields();
    for (Map.Entry<String, java.util.List<String>> entry : headerFields.entrySet()) {
      responseHeaders.append(entry.getKey()).append(": ").append(String.join(",", entry.getValue())).append("\n");
    }

    connection.disconnect();


    return getResponseStr(responseHeaders);
  }

  private static String getResponseStr(StringBuilder responseHeaders) {
    String resp = responseHeaders.toString();
//    System.out.println("====================响应体====================");
//    System.out.println(resp);
    return resp;
  }

}
